using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace InfraStructureLayer
{
    public class ObjectPropertyComparer<T> : IComparer<T>
    {
        PropertyInfo _property;
        public ObjectPropertyComparer(string propertyName)
        {
            MemberInfo[] members = typeof(T).GetMember(propertyName, MemberTypes.Property, BindingFlags.Instance | BindingFlags.Public);
            if (1 != members.Length)
            {
                throw new ArgumentException(string.Format("Could not resolve the property name \"{0}\"!", propertyName), propertyName);
            }
            _property = (PropertyInfo)members[0];
        }
        public ObjectPropertyComparer(PropertyInfo property)
        {
            if (null == property)
            {
                throw new ArgumentNullException("property");
            }
            _property = property;
        }
        public int Compare(T lhs, T rhs)
        {
            object lhsValue = _property.GetValue(lhs, null);
            object rhsValue = _property.GetValue(rhs, null);
            int value = 0;
            if (null != lhsValue)
            {
                value = ((IComparable)lhsValue).CompareTo(rhsValue);
            }
            else if (null != rhsValue)
            {
                value = ((IComparable)rhsValue).CompareTo(lhsValue);
                value *= -1;
            }
            return value;
        }
    }
}
